package com.imagefake.config.handler;

import com.alibaba.fastjson2.JSON;
import com.imagefake.util.JwtRedisUtil;
import com.imagefake.vo.HttpResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
@Slf4j
public class AppLogoutSuccessHandler implements LogoutSuccessHandler {
    @Resource
    private JwtRedisUtil jwtRedisUtil;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //设置响应编码
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        //从请求头中获取Authorization信息
        String authorization = request.getHeader("Authorization");
        //如果授权信息为空，返回前端
        if (null == authorization) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=utf-8");
            HttpResult httpResult = HttpResult.builder().code(-1).msg("token不能为空").build();
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(httpResult));
            writer.flush();
            return;
        }

        //如果Authorization信息不为空，去掉头部的Bearer字符串
        String jwtToken = authorization.replace("Bearer ", "");
        //删除Redis中的用户JWT以及权限信息
        if (jwtRedisUtil.deleteJwt(jwtToken)) {
            //删除成功
            HttpResult httpResult = new HttpResult(200, "退出成功");
            //把result转成JSON
            String httpResultJSON = JSON.toJSONString(httpResult);
            response.getWriter().write(httpResultJSON);
            response.getWriter().flush();
        } else {
            //删除失败
            HttpResult httpResult = new HttpResult(-1, "退出失败");
            //把result转成JSON
            String httpResultJSON = JSON.toJSONString(httpResult);
            response.getWriter().write(httpResultJSON);
            response.getWriter().flush();
        }

    }
}
